package com.neo.push.core.codec;

import com.neo.push.core.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by lock on 17-7-11.
 */
public class MessageEncoderHandler extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        try{
            byteBuf.writeInt(message.length());
            byteBuf.writeShort(message.type());
            if(null!=message.content()&&message.content().length != 0){
                byteBuf.writeBytes(message.content());
            }
            channelHandlerContext.writeAndFlush(byteBuf);
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }

    }


}
